#include <stdio.h>
#include <mysql.h>
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include "usrlib.h"
using namespace std;


//返回-1表示密码错误   -2表示用户不存在   0表示登录成功
int USRLIB::log_in(const char* name, const char* pwd)
{
	string cmd = "SELECT pwd FROM usr_info where usr_name = '";
	cmd += name;
	cmd += "'";

	int res = mysql_query(db,cmd.c_str());
	if( res )
	{
		cerr << "select error" << endl;
		exit(1);
	}

	MYSQL_RES * result = mysql_store_result(db);
	if( result == NULL )
	{
		cerr << "mysql_store_result error" << endl;
		exit(1);
	}

	//用户名不存在
	if( mysql_num_rows(result) == 0 )
	{
		return -2;
	}

	MYSQL_ROW row = mysql_fetch_row(result);
	if( strcmp(pwd,row[0]) != 0 )
	{
		return -1;
	}

	return 0;
}

USRLIB::USRLIB()
{
	db = mysql_init(NULL);
	if( !db )
	{
		cerr << "mysql_init failed" << endl;
		exit(1);
	}

	db = mysql_real_connect(db,"localhost",NULL,"clotshabby","gsync",0,NULL,0);
	if( !db )
	{
		cerr << "sql connect failed" << endl;
		exit(1);
	}
}

USRLIB::~USRLIB()
{
	mysql_close(db);
}

int USRLIB::add_usr(const char* name, const char* pwd)
{
	string cmd = "INSERT INTO usr_info VALUES('";
	cmd += name;
	cmd += "' , '";
	cmd += pwd;
	cmd += "')";

	int res = mysql_query(db,cmd.c_str());
	if( res )
	{
		return -1;
	}

	return 0;
}

